package com.jie;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Random;

public class TranslateMain {
    // 在百度翻译开发平台申请的APP ID和密钥
    private static final String APP_ID = "你的百度appid";
    private static final String SECURITY_KEY = "你的百度密钥";
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("使用方法: fanyi \"要翻译的文本\" [zh/en]");
            System.exit(1);
        }

        String query = args[0];
        String to;

        // 如果用户没有指定目标语言，自动检测
        if (args.length == 1) {
            to = isChineseText(query) ? "en" : "zh";
        } else {
            to = args[1];
        }

        String from = "auto";
        try {
            String result = translate(query, from, to);
            System.out.println("翻译结果：" + result);
        } catch (Exception e) {
            System.err.println("翻译出错：" + e.getMessage());
        }
    }

    // 判断文本是否包含中文
    private static boolean isChineseText(String text) {
        for (char c : text.toCharArray()) {
            if (Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN) {
                return true;
            }
        }
        return false;
    }

    private static String translate(String query, String from, String to) throws IOException {
        String salt = String.valueOf(new Random().nextInt(10000));
        String sign = DigestUtils.md5Hex(APP_ID + query + salt + SECURITY_KEY);

        String url = TRANS_API_HOST + "?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) +
                "&from=" + from +
                "&to=" + to +
                "&appid=" + APP_ID +
                "&salt=" + salt +
                "&sign=" + sign;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/json;charset=utf-8");

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);

                ObjectMapper mapper = new ObjectMapper();
                JsonNode root = mapper.readTree(result);

                if (root.has("error_code")) {
                    throw new IOException("翻译失败，错误码：" + root.get("error_code").asText() +
                            "，错误信息：" + root.get("error_msg").asText());
                }

                return root.get("trans_result").get(0).get("dst").asText();
            }
        }
    }
}